import React, {Component} from 'react';
import {
    Table,
    Row,
    Col,
    Descriptions,
    Form,
    Select,
    Input,
    Modal,
    DatePicker,
    Switch,
    message,
    Card,
    Button,
    Spin,
    Upload
} from 'antd';
import "./index.less";
import {PlusOutlined} from '@ant-design/icons';
import {withRouter} from "react-router-dom";
import {getMerById, getDicByType, getTitlePicDelete} from "@/api/api";
import E from 'wangeditor'

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {confirm} = Modal;
const {TextArea} = Input;
const reqUrl = 'http://localhost:5000/upLoadArticlePicture'
let editor1;

class goodEdit extends Component {
    componentWillReceiveProps(nextProps) {
        !nextProps.visible && this.props.form.resetFields();
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    constructor(props) {
        super(props);
        this.onChangeVal = this.onChangeVal.bind(this);
        this.onePictureBeforeUpload = this.onePictureBeforeUpload.bind(this);
        this.state = {
            dataSource: {},
            loading: false,
            oneTypeList: [],
            typeList: [],
            typeName: '',
            onePicture: [],
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            editorContent: '',
        };
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    componentDidMount() {
        this.getInfo()
        this.getDicByTypeList({level: '1'})
        this.getEditor()//初始化editor

    }

    getEditor() {
        const elemMenu = this.refs.editorElemMenu;
        const elemBody = this.refs.editorElemBody;
        const editor = new E(elemMenu, elemBody)
        editor.create()
    }

    getInfo() {
        let goodId = ''
        if (this.props.location.query) {
            goodId = this.props.location.query.id
            sessionStorage.setItem('goodId', goodId);// 存入到sessionStorage中
        } else {
            goodId = sessionStorage.getItem('goodId');
        }
        getMerById({id: goodId}).then(res => {
            console.log(res.data)
            if (res.code == 0) {
                this.setState({
                    loading: false,
                    dataSource: res.data
                })
                this.getTwoType({pid: res.data.oneType})
            }
        })
    }

    getDicByTypeList(params) {
        getDicByType(params).then((res) => {
            if (res.msg == "true") {
                this.setState({
                    oneTypeList: res.data
                })
            }
        })
    }

    getTwoType(params) {
        getDicByType(params).then((res) => {
            if (res.msg == "true") {
                let typeList = res.data
                let newTestData = Object.assign(this.state.dataSource, {['typeName']: typeList[0].name}); // 克隆新的对象赋值
                this.setState({
                    dataSource: newTestData,
                    typeList: typeList,
                })
            }
        })
    }

    changeType(id) {
        this.getTwoType({pid: id})
    }

    onChangeVal(type, e) {
        console.log(type)
        let val = '', status = 2, isOrder = 2
        if (type == 'name') {
            val = e.target.value
        } else if (type == 'oneTypeName') {
            val = e
            this.changeType(e)
        } else if (type == 'typeName') {
            val = e
        } else if (type == 'status') {
            e == true ? status = '2' : status = '1'
            val = status
        } else if (type == 'isOrder') {
            e == true ? isOrder = '2' : isOrder = '1'
            val = isOrder
        }
        let newTestData = Object.assign(this.state.dataSource, {[type]: val}); // 克隆新的对象赋值
        console.log(newTestData)
        this.setState({
            dataSource: newTestData,
        })
    }

    getBase64(file, callback) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => {
                callback(reader.result)
                resolve()
            }
            reader.onerror = error => reject(error);
        });
    }

    handleCancel = () => this.setState({previewVisible: false});
    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await this.getBase64(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };
    handleChange = ({onePicture}) => this.setState({onePicture});

    // 删除标题图片
    handleRemoveOnePicture(file) {
        if (file.id) {
            getTitlePicDelete({id: file.id}).then(res => {
                this.setState({
                    onePicture: []
                })
            })
        }
    }

    onePictureBeforeUpload(file) {
        const that = this
        that.getBase64(file, (imageUrl) => {
            file['url'] = imageUrl
            that.setState({
                onePicture: [file],
            })
        })
        return false;
    }

    render() {
        let pageInfo = JSON.parse(JSON.stringify(this.state.dataSource))
        const getOneStatusOption = this.state.oneTypeList.map((item) => <Option value={item.id}
                                                                                key={item.id}>{item.name}</Option>);
        const getTwoStatusOption = this.state.typeList.map((item) => <Option value={item.id}
                                                                             key={item.id}>{item.name}</Option>);
        const {previewVisible, previewImage, previewTitle} = this.state;
        const onePicture = this.state.onePicture || []
        const fileList = this.state.fileList || []
        const uploadButton = (
            <div>
                <PlusOutlined/>
                <div style={{marginTop: 8}}>标题上传</div>
            </div>
        );
        const sampleImageButton = (
            <div>
                <PlusOutlined/>
                <div style={{marginTop: 8}}>样例图片上传</div>
            </div>
        );
        const props = {
            onRemove: this.handleRemoveOnePicture,
            fileList: this.state.onePicture,
            listType: "picture-card",
            onPreview: this.handlePreview,
            onChange: this.handleChange,
            beforeUpload: this.onePictureBeforeUpload,
        }
        return (
            <div className="site-card-wrapper">
                <Spin spinning={this.state.loading} delay={500}>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Card title="产品原始信息" style={{height: 260}}>
                                <ul className="productInfo">
                                    <li><span>产品名称</span>{pageInfo.productName}</li>
                                    <li><span>产品原更新时间</span>{pageInfo.updateTime}</li>
                                    <li><span>产品版本</span>{pageInfo.version}</li>
                                    <li><span>产品id</span>{pageInfo.productId}</li>
                                </ul>
                            </Card>
                        </Col>
                        <Col span={12}>
                            <Card title="商品信息" style={{height: 260}}>
                                <Form className="search-form">
                                    <Row gutter={20}>
                                        <Col span={24}>
                                            <FormItem label="商品名称">
                                                <Input name='name' placeholder="请输入商品名称" value={pageInfo.name}
                                                       onChange={((e) => this.onChangeVal('name', e))}/>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row gutter={20}>
                                        <Col span={12}>
                                            <FormItem label="一级分类">
                                                <Select placeholder="请选择" value={pageInfo.oneTypeName}
                                                        name='oneTypeName'
                                                        onChange={((e) => this.onChangeVal('oneTypeName', e))}
                                                >
                                                    {getOneStatusOption}
                                                </Select>
                                            </FormItem>
                                        </Col>
                                        <Col span={12}>
                                            <FormItem label="二级分类">
                                                <Select placeholder="请选择" value={pageInfo.typeName}
                                                        name='typeName'
                                                        onChange={((e) => this.onChangeVal('typeName', e))}
                                                >
                                                    {getTwoStatusOption}
                                                </Select>

                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row gutter={20}>
                                        <Col span={12}>
                                            <FormItem label="是否上架">
                                                <Switch checkedChildren="开启" unCheckedChildren="关闭"
                                                        defaultChecked={pageInfo.status == '2'}
                                                        onClick={(e) => this.onChangeVal('status', e)}/>

                                            </FormItem>
                                        </Col>
                                        <Col span={12}>
                                            <FormItem label="是否可订购">
                                                <Switch checkedChildren="开启" unCheckedChildren="关闭"
                                                        defaultChecked={pageInfo.isOrder == '2'}
                                                        onClick={(e) => this.onChangeVal('isOrder', e)}/>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Card>
                        </Col>
                    </Row>
                    <Row gutter={16} justify="center" align="middle" className="marginTop10">
                        <Col span={4}>
                            <Card title="标题信息" style={{height: 200}}>
                                <Upload
                                    {...props}
                                >
                                    {onePicture.length >= 1 ? null : uploadButton}
                                </Upload>
                                <Modal visible={previewVisible}
                                       title={previewTitle}
                                       footer={null}
                                       onCancel={this.handleCancel}>
                                    <img alt="example" style={{width: '100%'}} src={previewImage}/>
                                </Modal>
                            </Card>
                        </Col>
                        <Col span={20}>
                            <Card title="标题介绍" style={{height: 200}}>
                                <TextArea style={{height: '300px'}}
                                    // value={value}
                                    // onChange={this.onChange}
                                          placeholder="请输入标题"
                                          autoSize={{minRows: 4, maxRows: 4}}></TextArea>
                            </Card>
                        </Col>

                    </Row>
                    <Row gutter={16} justify="center" align="middle" className="marginTop10">
                        <Col span={4}>
                            <Card title="标题信息" style={{height: 200}}>
                                <Upload
                                    {...props}
                                >
                                    {onePicture.length >= 1 ? null : uploadButton}
                                </Upload>
                                <Modal visible={previewVisible}
                                       title={previewTitle}
                                       footer={null}
                                       onCancel={this.handleCancel}>
                                    <img alt="example" style={{width: '100%'}} src={previewImage}/>
                                </Modal>
                            </Card>
                        </Col>
                        <Col span={20}>
                            <Card title="商品介绍" style={{height: 300}}>
                                <div>
                                    <div ref="editorElemMenu"
                                         style={{backgroundColor: '#f1f1f1', border: "1px solid #ccc"}}>
                                    </div>
                                    <div ref="editorElemBody" style={{
                                        height: 100,
                                        border: "1px solid #ccc",
                                        borderTop: "none",
                                        zIndex: 20
                                    }}>
                                    </div>
                                </div>
                            </Card>
                        </Col>

                    </Row>
                </Spin>
            </div>
        );
    }
}

export default withRouter(goodEdit)
// export default Form.create()(goodEdit);
